<template>
  <page-header-wrapper>
    <a-card>
      <div class="flex justify-between my-4">
        <span class="text-lg">违约程序</span>
        <a-button type="primary" @click="submit">保存</a-button>
      </div>
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :hideRequiredMark="true"
      >
        <div class="grid grid-cols-2 mx-8 mt-4">
          <a-form-model-item label="程序：" prop="pushType">
            <a-select v-model="form.pushType" :disabled="Archive == 1">
              <a-select-option :value="1">
                Default Notice
              </a-select-option>
              <a-select-option :value="2">
                Letter of Demand
              </a-select-option>
              <a-select-option :value="3">
                Perperty Law Act/Enforcement Notice
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="发出日期" prop="sendTime">
            <a-date-picker v-model="form.sendTime" @change="change" :disabled="Archive == 1" />
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2 mx-8 mt-4" v-if="form.pushType != 3">
          <a-form-model-item label="跟进日期：">
            <a-date-picker v-model="form.pushTime" disabled />
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2 mx-8 mt-4" v-if="form.pushType == 3">
          <a-form-model-item label="消息提示：" prop="messageContent">
            <a-textarea class="text" :rows="4" v-model="form.messageContent" :disabled="Archive == 1" />
          </a-form-model-item>
        </div>
      </a-form-model>
      <div class="flex justify-between my-4">
        <span class="text-lg">文件</span>
        <a-upload :showUploadList="false" :customRequest="upload" accept=".doc,.docx,.pdf,.xlsx,.xls,image/*">
          <a-button :loading="uploading" type="primary">上传文件</a-button><br />
        </a-upload>
      </div>

      <span class="flex justify-end"> 支持扩展名：.doc、.docx、.pdf、.xlsx、.xls、image/* </span><br />
      <a-table rowKey="id" :columns="columns" :data-source="data">
        <span slot="updateTime" slot-scope="updateTime"> {{ humanizeDate(updateTime) }}</span>
        <template slot="opt" slot-scope="text, record">
          <a @click="download(record)">查看</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除吗?" @confirm="() => onDelete(record.id)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import {
  creatFile,
  getFile,
  deleteFile,
  createStationLetterTemp,
  updataStationLetterTemp,
  getStationLetterTemp,
  getDetailList
} from '@/api/common'
import moment from 'moment'
import OSSClient from '@/utils/oss'
import form from '@/locales/lang/zh-CN/form'
import { commonRule, dateRule } from '@/utils/rules'
const client = new OSSClient()
const columns = [
  { dataIndex: 'ids', key: 'ids', title: '编号' },
  { dataIndex: 'fileName', key: 'fileName', title: '文件名称' },
  { dataIndex: 'updateTime', key: 'updateTime', title: '上传日期', scopedSlots: { customRender: 'updateTime' } },
  { dataIndex: 'fileFormat', key: 'fileFormat', title: '文件格式' },
  { dataIndex: 'opt', key: 'opt', title: '操作', scopedSlots: { customRender: 'opt' } }
]
export default {
  name: 'program',
  data() {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 10 },
      formId: '',
      Archive: 0,
      form: {
        pushType: 1,
        sendTime: '',
        pushTime: '',
        messageContent: ''
      },
      rules: {
        pushType: commonRule,
        sendTime: dateRule,
        messageContent: commonRule
      },
      columns,
      data: [],
      uploading: false
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    change() {
      this.form.pushTime = moment(this.form.sendTime + 2 * 24 * 60 * 60 * 1000, 'x')
    },
    async submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const _form = Object.assign({}, this.form)
          if (!(_form.pushType == 3)) {
            delete _form.messageContent
          }
          _form.pushTime = Number(_form.pushTime.startOf('day').format('X'))
          _form.sendTime = Number(_form.sendTime.startOf('day').format('X'))
          _form.projectId = this.$route.query.projectId
          _form.defaultDetailId = this.$route.query.defaultDetailId
          if (this.formId) {
            await updataStationLetterTemp(this.formId, _form)
            this.$router.back(-1)
          } else {
            await createStationLetterTemp(_form)
            this.$router.back(-1)
          }
        }
      })
    },
    download(record) {
      let suffix = record.fileUrl.split('.').pop()
      if (['doc', 'docx', 'xls', 'xlsx'].includes(suffix)) {
        window.open(`https://view.officeapps.live.com/op/view.aspx?src=${window.encodeURIComponent(record.fileUrl)}`)
      } else {
        window.open(record.fileUrl)
      }
    },
    humanizeDate(v) {
      if (v) {
        return moment(v * 1000).format('YYYY-MM-DD') || '--'
      } else {
        return '-'
      }
    },
    onSubmit() {
      this.$store.commit('form/CLEAR', 'business/ProjectBrief')
      this.$emit('submit')
      this.$router.push({ name: 'business/List' })
    },
    async onDelete(id) {
      await deleteFile(id)
      this.getData()
    },
    async getData() {
      const id = this.$route.query.projectId
      const r = await getDetailList(id)
      this.Archive = r.result.data.Archive
      let count = 0
      const res = await getFile({
        projectId: id,
        relationType: 5
      })
      this.data = res?.result?.data || []
      this.data.forEach(el => {
        el.ids = ++count
      })
      const data = await getStationLetterTemp({
        projectId: this.$route.query.projectId,
        defaultDetailId: this.$route.query.defaultDetailId
      })
      const _form = data.result.data.list[0]
      this.formId = _form.id
      for (let k in this.form) {
        this.form[k] = _form[k]
      }
      this.form.pushTime = moment(this.form.pushTime * 1000) || '--'
      this.form.sendTime = moment(this.form.sendTime * 1000) || '--'
    },
    async upload(obj) {
      try {
        this.uploading = true
        let url = await client.upload(obj.file, this.id, 5)
        await this.createFile(obj.file.name, url)

        this.uploading = false
        this.$message.success('上传成功')
        this.getData()
      } catch (err) {
        console.error(err)
        this.$message.error('上传失败')
      }
    },
    async createFile(filename, url) {
      let [name, suffix] = filename.split('.')
      const data = {
        fileName: name,
        fileFormat: suffix,
        projectId: this.$route.query.projectId,
        relationType: 5,
        fileUrl: url
      }
      return await creatFile(data)
    }
  }
}
</script>
<style lang="css" scoped>
.text {
  resize: unset;
  vertical-align: top;
}
</style>
